package com.efun.framework.util;

import org.beetl.core.Configuration;
import org.beetl.core.ConsoleErrorHandler;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.beetl.ext.fn.GetValueFunction;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Map;

/**
 * 利用beetlkit的自带功能完成字符串的转换
 * <pre>
 *
 *     BeetlKit.render("hello ${name}",JsonKit.toMap(\"name\":\"world\"));
 * </pre>
 * @author  kinven on 17/8/20.
 */
public class BeetlKit {

    private static GroupTemplate gt = null;

    protected static GroupTemplate getInstance(){
        if(gt == null) {
            StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
            Configuration cfg;
            try {
                cfg = Configuration.defaultConfiguration();

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            gt = new GroupTemplate(resourceLoader, cfg);
            gt.registerFunction("beetlKit", new GetValueFunction());
            gt.setErrorHandler(new ConsoleErrorHandler() {
                protected void println(Writer w, String msg) {
                    try {
                        w.write(msg);
                        w.write('\n');
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                protected void print(Writer w, String msg) {
                    try {
                        w.write(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                protected void printThrowable(Writer w, Throwable t) {

                    t.printStackTrace(new PrintWriter(w));
                }

                protected String getResourceName(String resourceId) {
                    if (resourceId.length() > 10) {
                        return resourceId.substring(0, 10).concat("...");
                    } else {
                        return resourceId;
                    }
                }
            });
        }
        return gt;
    }

    /** 渲染模板
     * @param template
     * @param paras
     * @return 模板返回值
     */
    public static <T> String render(String template, Map<String, T> paras)
    {
        Template t = getInstance().getTemplate(template);
        t.binding(paras);
        return t.render();
    }

    /** 渲染模板
     * @param template
     * @param writer
     * @param paras
     */
    public static <T> void renderTo(String template, Writer writer, Map<String, T> paras)
    {
        Template t = getInstance().getTemplate(template);
        t.binding(paras);
        t.renderTo(writer);
    }
}
